from datetime import datetime
from functools import wraps
import os
import loguru
import yaml

_current_date = datetime.now().date()
_current_path = os.path.abspath(__file__)
_root_path = os.path.dirname(os.path.dirname(_current_path))
_logs_path = os.path.join(_root_path, "logs")
_conf_path = os.path.join(_root_path, "utils", "conf")


# 单例类的装饰器
def singleton_class_decorator(cls):
    """
    装饰器，单例类的装饰器
    """
    # 在装饰器里定义一个字典，用来存放类的实例。
    _instance = {}

    # 装饰器，被装饰的类
    @wraps(cls)
    def wrapper_class(*args, **kwargs):
        # 判断，类实例不在类实例的字典里，就重新创建类实例
        if cls not in _instance:
            # 将新创建的类实例，存入到实例字典中
            _instance[cls] = cls(*args, **kwargs)
        # 如果实例字典中，存在类实例，直接取出返回类实例
        return _instance[cls]

    # 返回，装饰器中，被装饰的类函数
    return wrapper_class


@singleton_class_decorator
class Logger:
    def __init__(self):
        self.logger_add()

    def logger_add(self):
        try:
            with open(os.path.join(_conf_path, 'logs.yaml'), "r", encoding='utf-8') as file:
                config = yaml.safe_load(file)
                loguru.logger.add(
                    sink=os.path.join(_logs_path, f'file_{_current_date}.log'),
                    level=config.get("level"),
                    format=config.get("format"),
                    rotation=config.get("rotation"),
                    retention=config.get("enqueue")
                )
        except Exception as e:
            loguru.logger.error(f"Error parsing YAML file: {e}")

    @property
    def get_logger(self):
        return loguru.logger


logger = Logger().get_logger

if __name__ == '__main__':
    logger.info('----原始测试----')
